import logging
# logging.basicConfig(
#     level=logging.INFO,
#     filename='/Users/lijia/PycharmProjects/user-insight/insight_agent/agent_langgraph_qiutingli/output/server.log',
#     filemode='w'
# )

# Allow running this file directly without package context
import sys
from pathlib import Path
_SRC_DIR = Path(__file__).resolve().parent.parent  # .../insight_agent/mcp_server_graph/src
if str(_SRC_DIR) not in sys.path:
    sys.path.insert(0, str(_SRC_DIR))

from mcp.server.fastmcp import FastMCP

# 使用绝对导入，配合上面的 sys.path 注入，支持直接运行本文件
from mcp_server_graph.utils.graph_service import GraphService
from mcp_server_graph.llm.analyst_agent import AnalystAgent
from mcp_server_graph.llm.purpose_agent import PurposeAgent
from mcp_server_graph.utils.http_post import *
from mcp_server_graph.utils.data_handler import get_analyst_agent_input

# 初始化 MCP 服务器
mcp = FastMCP("GraphServer",
              port=8181,
              )

# 初始化群组处理程序
purpose_agent = PurposeAgent()  # 意图识别智能体
analyst_agent = AnalystAgent()  # 分析智能体

graph_service = GraphService()


def get_default(purpose, ids):
    if ids and isinstance(ids, list) and len(ids) > 0:
        return ids
    elif purpose == 0:
        return ['U02369', 'U00674']
    elif purpose == 1:
        return ['U02369']
    elif purpose == 2:
        return ['U02369']
    elif purpose == 3:
        return ['U00026']
    elif purpose == 4:
        return ['U01118', 'U01117', 'U00871', 'U01730', 'U00027', 'U01878', 'U02106', 'U00511', 'U01118', 'U01035',
                'U02183', 'U00005', 'U01131']
    elif purpose == 5:
        return ['U01118', 'U01117', 'U01137']


@mcp.tool()
async def graph_tool(ids="", user_request=""):
    """
    使用以自然人为中心构建的图数据，根据用户问题进行图查询，当提到人车家、异网拉新、存量运营、诈骗识别、用户细分、使用图数据库、使用图工具这些词时，务必调用此工具，返回某场景下的用户子图结构和解读
    业务场景解释
    1. 人车家：基于用户对4S店的访问和懂车帝APP的使用，判断用户可能存在购车需求，并根据用户家庭人数推荐车型
    2. 异网拉新：基于用户白天常驻基站和通信关系，聚合用户为地理圈群体，我们判断同一个地理圈的用户有类似的需求，我们基于每个地理圈的资费和APP使用偏好来制定圈内异网用户的拉新策略。异网用户指的是运营商非移动的用户，拉新指的是我们将异网用户推荐成为移动的新客户。
    3. 存量运营：基于地理圈群体和群体的资费和APP情况，我们判断同一个地理圈的用户有类似的需求，对群体内资费等偏低的用户进行产品营销推荐
    4. 诈骗识别：当一个新注册号码有大量呼出并且是漫游状态，很可能具有电诈风险
    5. 用户细分：查询集团用户群体中个人订购较多的产品，并发掘产品的潜在合作企业，制定推荐策略
    6. 其他图查询问题：当想查找用户多度关系但是不归类于上述5个图查询业务场景时，默认进行普通的二度查询
    常见问题有：
    "帮我找出北京地区经常去4S店，可能有购车意向的用户" (默认ids=['U02369','U00001']),
    "基于海淀区校园用户的特点，进行异网用户拉新"(默认ids=['U02925']),
    "日间常驻海淀区科技公司附近的用户群体中，哪些人资费明显低于其他人，请给出营销建议"(默认ids=['U02899', 'U00874']),
    "帮我筛查最近一周有大量短时长国际通话的新入网用户，识别诈骗风险"(默认ids=['U00026']),
    "查询集团用户群体中个人订购较多的产品，并发掘产品的潜在合作企业，制定推荐策略"(默认ids=['U01118', 'U01117', 'U00871', 'U01730', 'U00027', 'U01878', 'U02106', 'U00511', 'U01118', 'U01035', 'U02183', 'U00005', 'U01131']),
    "查询用户U02369的二度关系网络，识别高价值用户，并给出营销策略"(默认ids=['U02369','U02369','U00069'])
    :param ids: 用户id列表，可以为空，不要求一定传值
    :param user_request: 用户提出的问题
    :return: 图查询结果的解读
    """
    logging.info("自然人图谱模块工具被调用，获取到的id和问题：")
    logging.info(f"id:{ids}")
    logging.info(f"问题:{user_request}")
    logging.info("正在识别用户意图")
    data = purpose_agent.purpose_chat(user_request, [])
    purpose = data['purpose']  # 用户意图code （0～3）
    reason = data['reason']  # 用户意图判断依据

    summary = ""
    data = []
    answer = {"data": data, "summary": summary}
    subgraph_cypher = ""
    if purpose == 0:
        ids = get_default(purpose, ids)
        logging.info("用户意图识别为:人车家")
        logging.info(f"识别依据：{reason}")
        vertex_set, edge_set, subgraph_cypher, extra_info = graph_service.get_user_car_family(users=ids)
        data = {"vertexSet": vertex_set, "edgeSet": edge_set}
        logging.info("agent_graph已获得数据，准备进行数据解读")
        summary = analyst_agent.analyst_chat(get_analyst_agent_input(user_request, data, purpose, extra_info))
        logging.info("agent_graph已获得解读")

    elif purpose == 1:
        ids = get_default(purpose, ids)
        logging.info("用户意图识别为:异网用户发展")
        logging.info(f"识别依据：{reason}")
        vertex_set, edge_set, subgraph_cypher, extra_info = graph_service.get_new_customer_recommendation(users=ids)
        data = {"vertexSet": vertex_set, "edgeSet": edge_set}
        logging.info("agent_graph已获得数据，准备进行数据解读")
        summary = analyst_agent.analyst_chat(get_analyst_agent_input(user_request, data, purpose, extra_info))
        logging.info("agent_graph已获得解读")

    elif purpose == 2:
        ids = get_default(purpose, ids)
        logging.info("用户意图识别为:群体运营")
        logging.info(f"识别依据：{reason}")
        vertex_set, edge_set, subgraph_cypher, extra_info = graph_service.get_current_customer_recommendation(users=ids)
        data = {"vertexSet": vertex_set, "edgeSet": edge_set}
        logging.info("agent_graph已获得数据，准备进行数据解读")
        summary = analyst_agent.analyst_chat(get_analyst_agent_input(user_request, data, purpose, extra_info))
        logging.info("agent_graph已获得解读")

    elif purpose == 3:
        ids = get_default(purpose, ids)
        logging.info("用户意图识别为:诈骗识别")
        logging.info(f"识别依据：{reason}")
        vertex_set, edge_set, subgraph_cypher, extra_info = graph_service.get_fraud_meta(users=ids)
        data = {"vertexSet": vertex_set, "edgeSet": edge_set}
        logging.info("agent_graph已获得数据，准备进行数据解读")
        summary = analyst_agent.analyst_chat(get_analyst_agent_input(user_request, data, purpose, extra_info))
        logging.info("agent_graph已获得解读")

    elif purpose == 4:
        ids = get_default(purpose, ids)
        logging.info("用户意图识别为:用户细分")
        logging.info(f"识别依据：{reason}")
        vertex_set, edge_set, subgraph_cypher, extra_info = graph_service.get_group_product_recommendation(users=ids)
        data = {"vertexSet": vertex_set, "edgeSet": edge_set}
        logging.info("agent_graph已获得数据，准备进行数据解读")
        summary = analyst_agent.analyst_chat(get_analyst_agent_input(user_request, data, purpose, extra_info))
        logging.info("agent_graph已获得解读")

    elif purpose == 5:
        ids = get_default(purpose, ids)
        logging.info("用户意图识别为:二度查询")
        logging.info(f"识别依据：{reason}")
        vertex_set, edge_set, subgraph_cypher = graph_service.get_2_step_neighbour_meta(users=ids)
        data = {"vertexSet": vertex_set, "edgeSet": edge_set}
        logging.info("agent_graph已获得数据，准备进行数据解读")
        summary = analyst_agent.analyst_chat(get_analyst_agent_input(user_request, data, purpose))
        logging.info("agent_graph已获得解读")
    else:
        logging.info("意图识别错误")

    # data 字段处理
    data["resultSet"] = {
        "header": [],
        "table": []
    }
    data["errors"] = []
    data["groupSet"] = {}
    data["profile"] = {}
    data["vertexCount"] = len(data["vertexSet"])
    data["edgeCount"] = len(data["edgeSet"])
    data["resultCount"] = 1

    #summary处理
    summary = summary.replace('markdown', '')
    summary = summary.replace('```', '')

    if purpose in range(0, 6):
        answer = {"data": data, "summary": summary + f"\n\n生成的cypher语句：\n{subgraph_cypher}"}
    else:
        answer = {"data": None, "summary": "意图识别错误"}
    logging.info("agent_graph正在发送数据")

    update_insight_result(agent_type="agent_graph", updated_result=answer)
    logging.info("agent_graph发送数据结束")
    return summary


if __name__ == "__main__":
    # 以标准 I/O 方式运行 MCP 服务器
    mcp.run(transport='streamable-http')
